﻿using Common;
using Common.AVSPlatformAPI;
using Common.EF.Controllers;
using Common.Model;
using Common.Models;
using Common.Platform;
using Common.Utility;
using Common.Utility.AJ;
using Common.Utility.AJ.Extension;
using Masuit.Tools.Security;
using Stylet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace AWSV2.ViewModels
{
    public class CustomerRechargeDialogViewModel : AnnotationValidationScreen<CustomerRechargeForm>
    {
        private string _title;
        public string Title
        {
            get => _title;
            set => SetAndNotify(ref _title, value);
        }

        private AJErrorInfoDialogParams _errorInfo;
        public AJErrorInfoDialogParams ErrorInfo
        {
            get => _errorInfo;
            set => SetAndNotify(ref _errorInfo, value);
        }

        private bool _loading;
        public bool Loading
        {
            get => _loading;
            set => SetAndNotify(ref _loading, value);
        }

        private Dictionary<string, RechargeType> _rechargeTypeOptions;
        public Dictionary<string, RechargeType> RechargeTypeOptions
        {
            get => _rechargeTypeOptions;
            set => SetAndNotify(ref _rechargeTypeOptions, value);
        }

        private CustomerRechargeForm _form;
        public override CustomerRechargeForm Form
        {
            get => _form;
            set => SetAndNotify(ref _form, value);
        }

        public CustomerRechargeDialogViewModel(Customer customer)
        {
            ErrorInfo = new AJErrorInfoDialogParams();

            Title = I18NService.Translate(LangKeys._0_充值管理, customer.Name);

            RechargeTypeOptions = AJUtil.EnumToDictionary<RechargeType>(null);

            Form = new CustomerRechargeForm() { Customer = customer, Amount = "1" };
        }

        private bool _canCommit;
        public bool CanCommit
        {
            get
            {
                _canCommit = !Loading;
                return _canCommit;
            }
            set => SetAndNotify(ref _canCommit, value);
        }
        public async void Commit()
        {
            if (!ValidateModel())
            {
                ErrorInfo.Show(string.Join("\r\n", ValidationErrorsByProperty.SelectMany(p => p.Value).Select(p => p.ToString())));
                return;
            }
            var amount = Form.Amount.TryGetDecimal();

            if (amount == 0)
            {
                ErrorInfo.Show(I18NService.Translate(LangKeys.充值数量不正确请检查));
                return;
            }

            if (Globalspace._currentUser.LoginPwd != Form.Password)
            {
                Form.Password = string.Empty;
                ErrorInfo.Show(I18NService.Translate(LangKeys.登录密码不正确请重新输入));
                return;
            }

            Loading = true;

            // 同步到平台,如果对接的话
            if (PlatformManager.Instance.Current is AVSPlatformAPIManager avs)
            {
                var syncRet = await avs
                    .CustomerRechargeAsync(Form.Customer.Id, Form.AmountValue, Form.Remark, Form.Type);

                Form.UploadFlag = syncRet.Success;
                if (!Form.UploadFlag)
                {
                    Form.Remark ??= string.Empty;
                    Form.Remark += $" 同步失败:{syncRet.Message}";

                    AJLog4NetLogger.Instance().Error($"{Form.Customer.Name} 充值{Form.Type}失败:{syncRet.Message}");

                    MessageBox.Show(syncRet.Message, I18NService.Translate(LangKeys.充值信息同步失败), MessageBoxButton.OK);

                    Loading = false;
                    return;
                }
            }
            else
            {
                Form.UploadFlag = true;
            }

            try
            {
                using var ctrl = new CustomerController();
                var result = await ctrl.RechargeAsync(_form);

                RequestClose(true);
            }
            catch (Exception e)
            {
                ErrorInfo.Show(e.Message);
            }
            finally
            {
                Loading = false;
            }
        }
    }
}
